package com.dgut.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dgut.constant.MessageConstant;
import com.dgut.entity.Products;
import com.dgut.entity.SaleOrders;
import com.dgut.exception.RequireParameterException;
import com.dgut.mapper.ProductsMapper;
import com.dgut.mapper.SalesOrdersMapper;
import com.dgut.service.SalesOrdersService;
import com.dgut.vo.OrderVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class SalesOrdersServiceImpl implements SalesOrdersService {
    @Autowired
    private SalesOrdersMapper salesOrdersMapper;
    @Autowired
    private ProductsMapper productsMapper;

    /**
     * 根据合同id查询相关订单
     *
     * @param contractId
     * @return
     */
    @Override
    public List<OrderVO> getOrdersByContractId(Long contractId) {

        if (contractId == null) {
            throw new RequireParameterException(MessageConstant.REQUIRED_PARAMETER_IS_NULL);
        }

        QueryWrapper<SaleOrders> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("contract_id", contractId);
        List<SaleOrders> list = salesOrdersMapper.selectList(queryWrapper);

        //转换成OrderVO
        List<OrderVO> list1 = list.stream().map(orders -> {
            OrderVO orderVO = new OrderVO();
            BeanUtils.copyProperties(orders, orderVO);
            Products products = productsMapper.selectById(orders.getProductId());
            orderVO.setHandCount(products.getHandCount());
            return orderVO;
        }).collect(Collectors.toList());

        return list1;
    }

    /**
     * 根据id查询订单
     *
     * @param id
     * @return
     */
    @Override
    public SaleOrders getById(Long id) {
        return salesOrdersMapper.selectById(id);
    }

    /**
     * 修改订单
     *
     * @param orders
     */
    @Override
    public void updateById(SaleOrders orders) {
        salesOrdersMapper.updateById(orders);
    }
}
